<template>
  <a-modal
      :title="!dataForm.id ? '新增' : '修改'"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="保存"
      cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="dataForm" :model="dataForm" :rules="validatorRules">
        <a-form-model-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="username">
          <a-input placeholder="请输入用户账号" v-model="dataForm.username" :readOnly="!!dataForm.id" />
        </a-form-model-item>

        <template v-if="!dataForm.id">
          <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password">
            <a-input type="password" placeholder="请输入登录密码" v-model="dataForm.password" />
          </a-form-model-item>

          <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmPassword">
            <a-input type="password" placeholder="请重新输入登录密码" v-model="dataForm.confirmPassword" />
          </a-form-model-item>
        </template>

        <a-form-model-item label="用户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realName">
          <a-input placeholder="请输入用户姓名" v-model="dataForm.realName" />
        </a-form-model-item>

        <a-form-model-item label="工号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workNo">
          <a-input placeholder="请输入工号" v-model="dataForm.workNo" />
        </a-form-model-item>

        <a-form-model-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mobile">
          <a-input placeholder="请输入手机号码" v-model="dataForm.mobile" />
        </a-form-model-item>

        <a-form-model-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="email">
          <a-input placeholder="请输入邮箱" v-model="dataForm.email" />
        </a-form-model-item>

        <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-model="dataForm.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="角色分配" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-model="dataForm.roleIdList" placeholder="请选择角色" multiple has-feedback allow-clear>
            <a-select-option v-for="role in roleList" :key="role.id" :value="role.id">{{ role.name }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <!--部门分配-->
        <a-form-model-item label="部门分配" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <select-tree :options="departTree" v-model="dataForm.deptId"></select-tree>
        </a-form-model-item>

        <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-model="dataForm.status">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">冻结</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { duplicateCheck, queryDepartTreeList } from '@/api/api'
import { getAction, saveAction } from '@/api/manage'
import { isEmail, isMobile, isPassword } from '@/utils/validate'

export default {
  name: "user-from",
  data () {
    return {
      visible: false,
      confirmLoading: false,
      dataForm: {
        id: '',
        username: '',
        password: '',
        confirmPassword: '',
        realName: '',
        workNo: '',
        deptId: '',
        deptName: '',
        gender: 1,
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1,
      },
      roleList: [],
      departTree: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        save: "/sys/user",
        queryById: "/sys/user/edit",
        update: "/sys/user/edit"
      }
    }
  },
  computed: {
    validatorRules () {
      var validateUsername = (rule, value, callback) => {
        var params = {
          tableName: 'sys_user',
          fieldName: 'username',
          fieldVal: value,
          dataId: this.dataForm.id
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("用户名已存在!")
          }
        })
      }
      var validateWorkNo = (rule, value, callback) => {
        var params = {
          tableName: 'sys_user',
          fieldName: 'work_no',
          fieldVal: value,
          dataId: this.dataForm.id
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("工号已存在!")
          }
        })
      }
      var validatePassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          return callback('密码由8位数字、大小写字母和特殊符号组成!')
        }
        callback()
      }
      var validateConfirmPassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          return callback('密码由8位数字、大小写字母和特殊符号组成!')
        }
        if (this.dataForm.password !== value) {
          return callback('两次输入的密码不一致!')
        }
        callback()
      }
      var validateMobile = (rule, value, callback) => {
        if (isMobile(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'mobile',
            fieldVal: value,
            dataId: this.dataForm.id
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback("手机号已存在!")
            }
          })
        } else {
          callback("请输入正确格式的手机号!")
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (isEmail(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'email',
            fieldVal: value,
            dataId: this.dataForm.id
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback("邮箱已存在!")
            }
          })
        } else {
          callback("请输入正确格式的邮箱!")
        }
      }
      return {
        username: [
          { required: true, message: '请输入用户账号!' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码!' },
          { validator: validatePassword, trigger: 'change' }
        ],
        confirmPassword: [
          { required: true, message: '请输入登录密码!' },
          { validator: validateConfirmPassword, trigger: 'change' }
        ],
        realName: [
          { required: true, message: '请输入用户名称!' }
        ],
        mobile: [
          { required: true, message: '请输入手机号!' },
          { validator: validateMobile }
        ],
        email: [
          { required: true, message: '请输入邮箱!' },
          { validator: validateEmail }
        ],
        workNo: [
          { required: true, message: '请输入工号!' },
          { validator: validateWorkNo }
        ],
      }
    },
  },
  methods: {
    init () {
      this.visible = true
      this.dataForm.deptId = ''
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.confirmLoading = true
        Promise.all([
          this.getRoleList(),
          this.getDeptList()
        ]).then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
          this.confirmLoading = false
        })
      })
    },
    // 获取角色列表
    getRoleList () {
      return new Promise((resolve, reject) => {
        getAction('/sys/role/list').then((res) => {
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.roleList = res.result
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取部门列表
    getDeptList () {
      return new Promise((resolve, reject) => {
        queryDepartTreeList().then((res) => {
          if (!res.success) {
            return this.$message.error(res.message)
          }
          this.departTree = res.result
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    getInfo () {
      getAction(`${ this.url.queryById }/${ this.dataForm.id }`).then((res) => {
        if (!res.success) {
          return this.$message.error(res.message)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.result
        }
      }).catch(() => {
      })
    },
    handleOk () {
      const that = this;
      // 触发表单验证
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          // that.dataForm.roleIdList = that.dataForm.roleIdList ? that.dataForm.roleIdList.split(',') : []
          const actionUrl = that.dataForm.id ? that.url.update : that.url.save;
          saveAction(actionUrl, that.dataForm).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              this.$emit('ok')
            } else {
              that.$message.error(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.handleCancel();
          })
        }
      })
    },
    handleCancel () {
      this.visible = false;
    }
  }
}
</script>

<style scoped>

</style>
